package myExample;

import java.io.File;
import java.io.IOException;

import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.collection.CasConsumer;
import org.apache.uima.collection.CollectionProcessingManager;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.resource.ResourceConfigurationException;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;

public class CPMProvider {	
	private CollectionProcessingManager mCPM;
	private CollectionReader mCR;
	private AnalysisEngine mAe;
	private CasConsumer mCc;
	
	public CPMProvider() {		
	}
	
	public CPMProvider(String crDesc, String aeDesc, String ccDesc) {
		try {			
			mCPM = UIMAFramework.newCollectionProcessingManager();
			
			// find CR
			ResourceSpecifier colReaderSpecifier = UIMAFramework.getXMLParser()
					.parseCollectionReaderDescription(new XMLInputSource(crDesc));
			mCR = UIMAFramework.produceCollectionReader(colReaderSpecifier);
			
			// find AE
			ResourceSpecifier aeSpecifier = UIMAFramework.getXMLParser()
					.parseResourceSpecifier(new XMLInputSource(aeDesc));
		    mAe = UIMAFramework.produceAnalysisEngine(aeSpecifier);
		    
		    // find CC
		    ResourceSpecifier consumerSpecifier = UIMAFramework.getXMLParser()
		    		.parseCasConsumerDescription(new XMLInputSource(ccDesc));
		    mCc = UIMAFramework.produceCasConsumer(consumerSpecifier);
		    
		    mCPM.setAnalysisEngine(mAe);
		    mCPM.addCasConsumer(mCc);
		    mCPM.setPauseOnException(false);
		    	    
		} catch (InvalidXMLException e) {		
			e.printStackTrace();
		} catch (IOException e) {		
			e.printStackTrace();
		} catch (ResourceInitializationException e) {
			e.printStackTrace();
		} catch (ResourceConfigurationException e) {
			e.printStackTrace();
		}		
	}
	
	public void Process() {
		try {
			// delete old result :D
			File mOutput = new File("../MyExample/output/result.txt");
		    if (mOutput.exists()) {
		      mOutput.delete();
		    }
		    
			mCPM.process(mCR);			
		} catch (ResourceInitializationException e) {
			e.printStackTrace();
		} 
	}
	
}
